/*
 * @Description:
 * @Author: xuzp4
 * @Date: 2021-11-25 13:43:27
 * @LastEditors: xuzp4
 * @LastEditTime: 2021-11-30 13:59:52
 * @FilePath: \dms-lite-web-huashun\src\directive\el-table\adaptive.js
 */
/**
 * How to use
 * <el-table height="100px" v-el-height-adaptive-table="{bottomOffset: 30}">...</el-table>
 * el-table height is must be set
 * bottomOffset: 30(default)   // The height of the table from the bottom of the page.
 */

const doResize = (el, binding, vnode) => {
	const {
		componentInstance: $table
	} = vnode;

	const {
		value
	} = binding;

	if (!$table.height) {
		throw new Error(`el-$table must set the height. Such as height='100px'`);
	}
	const bottomOffset = (value && value.bottomOffset) || 100;

	if (!$table) return;

	const height = window.innerHeight - el.getBoundingClientRect().top - bottomOffset;
	setTimeout(() => {
		$table.layout.setHeight(height);
		$table.doLayout();
	}, 100);
};
let timer = null;
export default {
	bind(el, binding, vnode) {
		el.resizeListener = () => {
			clearTimeout(timer);
			timer = setTimeout(() => {
				doResize(el, binding, vnode);
			}, 100);
		};
		// parameter 1 is must be "Element" type
		window.addEventListener('resize', el.resizeListener);
	},
	inserted(el, binding, vnode) {
		doResize(el, binding, vnode);
	},
	update(el, binding, vnode) {
		doResize(el, binding, vnode);
	},
	unbind(el) {
		window.removeEventListener('resize', el.resizeListener);
	}
};
